import fs from 'fs'
import bluebird from 'bluebird'
import { postTB } from '../database/mongodb/index.js'
import { configObj } from '../node.config.js'
import { promisePool } from '../database/mysql2/index.js'
import { autoIncreaseId } from './tools.js'
bluebird.promisifyAll(fs)

let isMongoDB = configObj.argv[0] === 'mongodb'

// 文章数据
// const posts = []

// 文章ID

// let postId = 1

// 发表文章

export async function publish(title, content) {
  if (isMongoDB) {
    let id = await autoIncreaseId(postTB)
    const item = {
      id,
      title,
      content,
      time: new Date().toLocaleDateString()
    }
    // posts.push(item)
    let insertOne = await postTB.insertOne(item)
    // insertOne  insertMany
    console.log(`insertOne => %O `, insertOne)
    return item
  } else {
    let [resultSetHeader] = await promisePool.execute(
      `INSERT INTO post_tb (title,content,time) values("${title}","${content}","${new Date()
        .toISOString()
        .slice(0, 10)}")`
    )
    console.log(`resultSetHeader => %O `, resultSetHeader)
    return { id: resultSetHeader.insertId }
  }
}

// 查看文章
export async function show(id) {
  if (isMongoDB) {
    id = Number(id)
    let findOne = await postTB.findOne({ id })
    console.log(`findOne => %O `, findOne)
    return findOne
  } else {
    const [rows] = await promisePool.query(
      `SELECT * FROM post_tb WHERE id='${id}'`
    )
    console.log('rows=', rows)
    return rows[0]
  }
}

// 编辑文章
export async function update(id, title, content) {
  if (isMongoDB) {
    id = Number(id)
    let query = { id }
    let updateDoc = {
      $set: {
        title,
        content
      }
    }

    // 没有匹配项,则创建新的
    const options = { upsert: true }

    let updateOne = await postTB.updateOne(query, updateDoc, options)
    console.log(`updateOne => %O `, updateOne)
  } else {
    const [rows] = await promisePool.execute(
      `UPDATE post_tb SET title="${title}",content="${content}" WHERE id='${id}'`
    )
    console.log('rows=', rows)
    return rows[0]
  }
}

// 删除文章
export async function deleteOne(id) {
  if (isMongoDB) {
    id = Number(id)
    let query = { id }
    let deleteOne = await postTB.deleteOne(query)
    console.log(`deleteOne => %O `, deleteOne)
  } else {
    const [rows] = await promisePool.execute(
      `DELETE FROM  post_tb WHERE id='${id}'`
    )
    console.log('rows=', rows)
    // return rows[0]
  }
}

// 文章列表
export async function list() {
  if (isMongoDB) {
    // return posts.map(item => item)
    let findAll = await postTB.find({}).toArray()
    console.log(`findAll => %O `, findAll)
    return findAll
  } else {
    const [rows] = await promisePool.query(`SELECT * FROM post_tb`)
    console.log('rows=', rows)
    return rows
  }
}
